$(function	()	{
	//scrollable sidebar
	$('.scrollable-sidebar').slimScroll({
		height: '100%',
		size: '0px'
	});
	
	//Collapsible Sidebar Menu
	$('.sidebar-menu .openable > a').click(function()	{
		
		if(!$('aside').hasClass('sidebar-mini') || Modernizr.mq('(max-width: 991px)'))	{
			if( $(this).parent().children('.submenu').is(':hidden') ) {
				$(this).parent().siblings().removeClass('open').children('.submenu').slideUp(200);
				$(this).parent().addClass('open').children('.submenu').slideDown(200);
			}
			else	{
				$(this).parent().removeClass('open').children('.submenu').slideUp(200);
			}
		}
		
		return false;
	});
    /*
	//恢复菜单上次点击状态
	if(window.sessionStorage.getItem("active_2")){
        var selectors = window.sessionStorage.getItem("active_1");
        var selector = window.sessionStorage.getItem("active_2");
        $(selectors).parent("li.openable").addClass("open");
        $(selector).parent("li").addClass("active");
        window.sessionStorage.removeItem("active_1");
        window.sessionStorage.removeItem("active_2");
	}


    //记录菜单上次点击状态
    $(".main-menu .accordion .submenu li:not(.openable) a").click(function (event) {
        event.preventDefault();
        var url = $(this).attr("href");
        var active_1,active_2= [];
        active_1 = $.map($(".main-menu .accordion li.open > a"), function (val) {
			return "#"+$(val).attr("id");
        });

        active_2.push("#"+$(this).attr("id"));
        window.sessionStorage.setItem("active_1", active_1.join(","));
        window.sessionStorage.setItem("active_2", active_2);
        window.location.href = url;
    });
    */
	//Open active menu
	if(!$('.sidebar-menu').hasClass('sidebar-mini') || Modernizr.mq('(max-width: 767px)'))	{
		$('.openable.open').children('.submenu').slideDown(200);
	}
	
	//Toggle User container on sidebar menu
	$('#btn-collapse').click(function()	{
		$('.sidebar-header').toggleClass('active');
	});
	
	//theme setting
	$("#theme-setting-icon").click(function()	{ 
		if($('#theme-setting').hasClass('open'))	{
			$('#theme-setting').removeClass('open');
			$('#theme-setting-icon').removeClass('open');
		}
		else	{
			$('#theme-setting').addClass('open');
			$('#theme-setting-icon').addClass('open');
		}

		return false;
	});
	
	$('#sidebarToggleLG').click(function()	{
		if($('.wrapper').hasClass('display-right'))	{
			$('.wrapper').removeClass('display-right');
			$('.sidebar-right').removeClass('active');
		}
		else	{
			//$('.nav-header').toggleClass('hide');
			$('.top-nav').toggleClass('sidebar-mini');
			$('aside').toggleClass('sidebar-mini');
			$('footer').toggleClass('sidebar-mini');
			$('.main-container').toggleClass('sidebar-mini');
			
			$('.main-menu').find('.openable').removeClass('open');
			$('.main-menu').find('.submenu').removeAttr('style');
		}		
	});
	
	$('#sidebarToggleSM').click(function()	{
		$('aside').toggleClass('active');
		$('.wrapper').toggleClass('display-left');
	});


	$('.sidebarRight-toggle').click(function()	{
		$('.sidebar-right').toggleClass('active');
		$('.wrapper').toggleClass('display-right');
		$('footer').toggleClass('display-right');

		return false;
	});
	
	$('.dropdown-menu input').click(function(e) {
        e.stopPropagation(); //This will prevent the event from bubbling up and close the dropdown when you type/click on text boxes.
    });
	
	//to do list
	/*$('.task-finish').click(function()	{
		if($(this).is(':checked'))	{
			$(this).parent().parent().addClass('selected');					
		}
		else	{
			$(this).parent().parent().removeClass('selected');
		}
	});*/

	//Delete to do list
	/*$('.task-del').click(function()	{
		var activeList = $(this).parent().parent();

		activeList.addClass('removed');
				
		setTimeout(function() {
			activeList.remove();
		}, 1000);
			
		return false;
	});*/
	
	/*var $activeWidget = '';
	var $activeWidgetHeader;
	var $headerHeight;
	var $screenHeight;
	var $widgetHeight;
	var $borderHeight = 3;*/

	//Smart Widget

	// Refresh Widget
	/*$('.widget-refresh-option').click(function()	{

		$activeWidget = $(this).parent().parent().parent();
		
		var $activeSpinIcon = $activeWidget.find('.refresh-icon-animated').fadeIn();

		setTimeout(function() {
			$activeSpinIcon.fadeOut();
		},2000);

		return false;
	});*/

	// Collasible Widget
	/*$('.widget-collapse-option').click(function()	{
		$activeWidget = $(this).parent().parent().parent();

		$activeWidget.find('.smart-widget-inner').slideToggle();
		$activeWidget.toggleClass('smart-widget-collapsed');

		var $activeSpinIcon = $activeWidget.find('.refresh-icon-animated').fadeIn();

		setTimeout(function() {
			$activeSpinIcon.fadeOut();
		},500);

		$activeWidget = '';

		return false;
	});*/

	//Changing Widget Color
	/*$('.widget-toggle-hidden-option').click(function()	{
		$activeWidget = $(this).parent().parent().parent();

		$activeWidget.find('.smart-widget-hidden-section').slideToggle();	

		var $activeSpinIcon = $activeWidget.find('.refresh-icon-animated').fadeIn();

		setTimeout(function() {
			$activeSpinIcon.fadeOut();
		},500);


		$activeWidget = '';			

		return false;
	});*/

	//Changing Widget Header Background
	/*$('.widget-color-list li').click(function()	{
		$activeWidget = $(this).parent().parent().parent().parent();
		$selectedColor = $(this).data('color');

		$activeWidget.removeClass('widget-light-grey');
		$activeWidget.removeClass('widget-dark');
		$activeWidget.removeClass('widget-dark-blue');
		$activeWidget.removeClass('widget-blue');
		$activeWidget.removeClass('widget-green');
		$activeWidget.removeClass('widget-yellow');
		$activeWidget.removeClass('widget-orange');
		$activeWidget.removeClass('widget-red');
		$activeWidget.removeClass('widget-purple');

		if($selectedColor != 'reset')
			$activeWidget.addClass($selectedColor);
		
		return false;
	});*/

	// Remove Widget
	/*$('.widget-remove-option').click(function()	{

		$activeWidget = $(this).parent().parent().parent();

		$('#deleteWidgetConfirm').popup('show');

		return false;

	});

	$('.remove-widget-btn').click(function()	{
		$('#deleteWidgetConfirm').popup('hide');
		$activeWidget.fadeOut();

		$activeWidget = '';

		return false;
	});*/

	//Scroll to Top
	$(".scroll-to-top").click(function()	{
		$("html, body").animate({ scrollTop: 0 }, 600);
		 return false;
	});

	// Popover
    $("[data-toggle=popover]").popover();
	
	// Tooltip
    $("[data-toggle=tooltip]").tooltip();
	$("[rel=tooltip]").tooltip();
});

var error = '<div class="alert alert-danger alert-custom alert-dismissible">' +
    '<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>' +
    '<i class="fa fa-times-circle m-right-xs"></i>%0.</div>';

String.prototype.format=function()
{
    if(arguments.length==0) return this;
    for(var s=this, i=0; i<arguments.length; i++)
        s=s.replace(new RegExp("%"+i,"g"), arguments[i]);
    return s;
};

$(window).load(function() {
	$('body').removeClass('overflow-hidden');

	//Enable animation
	$('.wrapper').removeClass('preload');

	//Chat Notification on top navigation
	setTimeout(function() {
		$('.chat-notification').find('.badge').addClass('active');
		$('.chat-alert').addClass('active');
	}, 3000);

	setTimeout(function() {
		$('.chat-alert').removeClass('active');
	}, 8000);
});

// Toggle Scroll to Top button
$(window).scroll(function(){
		
	 var position = $(window).scrollTop();
	
	 if(position >= 200)	{
		$('.scroll-to-top').addClass('active')
	 }
	 else	{
		$('.scroll-to-top').removeClass('active')
	 }
});

function addRequestParamsters(single, src) {

    var isSet = [];
    var data = single.serializeArray();
    src.another = [];
    $.each(data, function (index, element) {
        if ($.inArray(element.name, isSet) > -1)
            return true;
        var selector = "input[name=" + element.name + "],select[name=" + element.name + "]";
        var selectorArray = $(selector).toArray();

        var values = $.map(selectorArray, function (n, i) {
            return $(n).val();
        });
        var key = $(selector).data('column');
        if (key >= 0 && key<= src.columns.length-1) {
            if (values.length > 1) {
                isSet.push(element.name);
                src.columns[key].search.value = values;

            } else {
                src.columns[key].search.value = values.join("");
            }

        } else {
            if (!values.length > 1) {
                src.another
                    .push({
                        data: $(selector).eq(0).attr("id"),
                        name: $(selector).eq(0).attr("name"),
                        search: {value: values}
                    });

            } else {
                values = values.join("");
                isSet.push(element.name);
                src.another
                    .push({
                        data: $(selector).attr("id"),
                        name: $(selector).attr("name"),
                        search: {value: values}
                    });
            }
        }
    });
    return src;
}

//多条件处理拼接
function joinCondition(single,more,src) {
	src.another =  new Array();
	var allCond = new Array();	//所有条件存放数组

	single.find("input,select").each(function(index,element){
		var doing = $(element).attr('doing');
		if(element.type !='button' && element.value !='') {
			allCond.push({'data': element.name, 'name': element.name, 'value': element.value, 'doing': doing});
		}
	 });
	if(more !=''){
		more.find("input,select").each(function(index,element){
			var doing = $(element).attr('doing');
			if(element.value != ''){
				allCond.push({'data':element.name,'name':element.name, 'value':element.value,'doing':doing});
			}
		});
	}

	var allLen = allCond.length;
	var srcLen = src.columns.length;

	for(var i=0;i<allLen;i++){

		if(allCond[i].doing==undefined){

			if( i!=0 && allCond[i].data==allCond[i-1].data && allCond[i].data !=''){

				allCond[i-1].name = 'BETWEEN_'+allCond[i].name;

				var sValue = allCond[i-1].value;
				var eValue = allCond[i].value;

				allCond[i-1].value = new Array();

				allCond[i-1].value.push(sValue);
				allCond[i-1].value.push(eValue);

				allCond[i].data = 'delete';

			}
		}
	}

	for(var i=0;i<allLen;i++) {
		var key = allCond[i].doing
		if (key != undefined) {
			src.columns[key].search.value = allCond[i].value;
		}
		if (key == undefined && allCond[i].data != 'delete' && allCond[i].value !='' ) {
			src.another.push({'data': allCond[i].data,'name':allCond[i].name,'search':{'value':allCond[i].value}})
		}
	}
	return src;
}
//时间初始化获取
function getTime(className, config){
    var options = {
        language:'ch',
        minView:'month',	//最小时间选择到month
        format:'yyyy-mm-dd hh:ii:ss',
        todayBtn:'linked',	//显示‘今天’按钮
        clearBtn:true,		//显示清除时间按钮
        autoclose:true,     //选中日期后日否立即关闭时间选择器
        todayHighlight:true //当前日期高亮显示
    };
    config = $.extend({}, options, config);
	$("."+className).datetimepicker(config);
}

//条件处理
function conditionManage(single,src) {
    src.another = new Array();
    single.find("input,select").each(function (index, element) {
        if (element.type != 'button' && element.value != '') {
            src.another.push({'data': element.id, 'value': element.value});
        }
    });
};
if($.fn.dataTable)
{
    $.fn.dataTable.pipeline = function ( opts ) {
        // Configuration options
        var conf = $.extend( {
            pages: 5,     // number of pages to cache
            url: '',       // script url
            data: null,    // function or object with parameters to send to the server
                           // matching how `ajax.data` works in DataTables
            method: 'POST' // Ajax HTTP method
        }, opts );

        // Private variables for storing the cache
        var cacheLower = -1;
        var cacheUpper = null;
        var cacheLastRequest = null;
        var cacheLastJson = null;

        return function ( request, drawCallback, settings ) {
            var ajax          = false;
            var requestStart  = request.start;
            var drawStart     = request.start;
            var requestLength = request.length;
            var requestEnd    = requestStart + requestLength;

            // Provide the same `data` options as DataTables.
            if ( $.isFunction ( conf.data ) ) {
                // As a function it is executed with the data object as an arg
                // for manipulation. If an object is returned, it is used as the
                // data object to submit
                var d = conf.data( request );
                if ( d ) {
                    $.extend( request, d );
                }
            }
            else if ( $.isPlainObject( conf.data ) ) {
                // As an object, the data given extends the default
                $.extend( request, conf.data );
            }

            if ( settings.clearCache ) {
                // API requested that the cache be cleared
                ajax = true;
                settings.clearCache = false;
            }
            else if ( cacheLower < 0 || requestStart < cacheLower || requestEnd > cacheUpper ) {
                // outside cached data - need to make a request
                ajax = true;
            }
            else if ( JSON.stringify( request.order )   !== JSON.stringify( cacheLastRequest.order ) ||
                JSON.stringify( request.columns ) !== JSON.stringify( cacheLastRequest.columns ) ||
                JSON.stringify( request.search )  !== JSON.stringify( cacheLastRequest.search )
            ) {
                // properties changed (ordering, columns, searching)
                ajax = true;
            }

            // Store the request for checking next time around
            cacheLastRequest = $.extend( true, {}, request );

            if ( ajax ) {
                // Need data from the server
                if ( requestStart < cacheLower ) {
                    requestStart = requestStart - (requestLength*(conf.pages-1));

                    if ( requestStart < 0 ) {
                        requestStart = 0;
                    }
                }

                cacheLower = requestStart;
                cacheUpper = requestStart + (requestLength * conf.pages);

                request.start = requestStart;
                request.length = requestLength*conf.pages;

                settings.jqXHR = $.ajax( {
                    "type":     conf.method,
                    "url":      conf.url,
                    "data":     request,
                    "dataType": "json",
                    "cache":    false,
                    "success":  function ( json ) {
                        cacheLastJson = $.extend(true, {}, json);

                        if ( cacheLower != drawStart ) {
                            json.data.splice( 0, drawStart-cacheLower );
                        }
                        if ( requestLength >= -1 ) {
                            json.data.splice( requestLength, json.data.length );
                        }

                        drawCallback( json );
                    }
                } );
            }
            else {
                json = $.extend( true, {}, cacheLastJson );
                json.draw = request.draw; // Update the echo for each response
                json.data.splice( 0, requestStart-cacheLower );
                json.data.splice( requestLength, json.data.length );

                drawCallback(json);
            }
        }
    };

// Register an API method that will empty the pipelined data, forcing an Ajax
// fetch on the next draw (i.e. `table.clearPipeline().draw()`)
    $.fn.dataTable.Api.register( 'clearPipeline()', function () {
        return this.iterator( 'table', function ( settings ) {
            settings.clearCache = true;
        } );
    } );
}
function getTableHeight() {
    return $(".wrapper").height() - $(".top-nav").height() - $(".footer").height() - $("#op-block").height();
}

function msg_alert(id,msg){

	$("#"+id+" .content").html(msg);
	$("#"+id).modal();
}


